package sau.diyizu.media.video;

import android.content.ContentResolver;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.RecyclerView;

import sau.diyizu.media.R;
import sau.diyizu.media.bean.Video;
import sau.diyizu.media.common.BaseFragment;

import java.util.ArrayList;
import java.util.List;

/**
 @author JYD
 @version 1.0
 @since 2020/12/15 20:17 */
public class VideosFragment extends BaseFragment {
    public static final String TAG = "VideosFragment";

    private RecyclerView content_rv;
    private VideoAdapter adapter;
    private View view;
    private boolean readPermissionEnabled = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_videos, container, false);
        adapter = new VideoAdapter();
        onBindView();
        onBindListener();
        onInitView();
        onLoadData();

        return view;
    }

    private void onBindView() {
        content_rv = view.findViewById(R.id.content_rv);
    }

    private void onBindListener() {
        adapter.setItemListener((view, pos, type) -> {
            String path = adapter.getVideoList().get(pos).path;
            Log.d(TAG, "onBindListener: path: " + path);
            startActivity(VideoActivity.createIntent(requireContext(), path));
        });
    }

    private void onInitView() {
        content_rv.setAdapter(adapter);
    }

    private void onLoadData() {
        if (!readPermissionEnabled) return;
        if (!getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.CREATED)) return;
        adapter.setDataAndNotify(getVideos(requireContext().getContentResolver()));
    }

    public List<Video> getVideos(ContentResolver contentResolver) {
        List<Video> videos = new ArrayList<>();
        try (Cursor c = contentResolver.query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                null, null, null,
                MediaStore.Video.Media.DEFAULT_SORT_ORDER)) {
            int idIndex = c.getColumnIndex(MediaStore.Video.Media._ID);
            int pathIndex = c.getColumnIndex(MediaStore.Video.Media.DATA);
            int nameIndex = c.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME);
            int resolutionIndex = c.getColumnIndex(MediaStore.Video.Media.RESOLUTION);
            int sizeIndex = c.getColumnIndex(MediaStore.Video.Media.SIZE);
            int durationIndex = 0;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                durationIndex = c.getColumnIndex(MediaStore.Video.Media.DURATION);
            }
            int dateIndex = c.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED);
            int widthIndex = c.getColumnIndex(MediaStore.Video.Media.WIDTH);
            int heightIndex = c.getColumnIndex(MediaStore.Video.Media.HEIGHT);


            while (c.moveToNext()) {
                String path = pathIndex != -1 ? c.getString(pathIndex) : null;
                Video video = new Video();
                video.id = getInt(c, idIndex);
                video.path = path;
                video.name = getString(c, nameIndex);
                video.resolution = getString(c, resolutionIndex);
                video.size = getLong(c, sizeIndex);
                video.duration = getLong(c, durationIndex);
                video.date = getLong(c, dateIndex);
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(path);
                video.width = getLong(c, widthIndex);
                video.height = getLong(c, heightIndex);
                videos.add(video);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return videos;
    }

    public void onReadPermissionUpdate(boolean enabled) {
        readPermissionEnabled = enabled;
        if (enabled) onLoadData();
    }
}
